package com.facexue.miniprogram.interceptor;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.servlet.HandlerInterceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.facexue.miniprogram.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
	
	@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
				throws Exception {
			// TODO Auto-generated method stub
		 Map<String, Object> map = new HashMap<>();
	        String token = request.getHeader("Authorization");
	        try {
	            JwtUtil.verify(token);
	            // 放行
	            return true;
	        } catch (SignatureVerificationException e) {
	            log.error("【请求失败】：{}", e.getMessage());
	            map.put("msg", "无效签名");
	        } catch (TokenExpiredException e) {
	            log.error("【请求失败】：{}", e.getMessage());
	            map.put("msg", "token过期");
	        } catch (AlgorithmMismatchException e) {
	            log.error("【请求失败】：{}", e.getMessage());
	            map.put("msg", "token算法不一致");
	        } catch (Exception e) {
	            log.error("【请求失败】：{}", e.getMessage());
	            map.put("msg", "token无效");
	        }
	        // 将错误消息返回给前台
	        map.put("status", false);
	        // 将Map转化为json字符串
	        String errorResult = new ObjectMapper().writeValueAsString(map);
	        response.setContentType("application/json;charset=UTF-8");
	        response.getWriter().println(errorResult);
	        return false;
		}
}
